package com.benz.project.pvm.controller.version;

import com.benz.project.pvm.controller.BaseController;
import com.benz.project.pvm.domain.Version;
import com.benz.project.pvm.http.param.version.VersionEntity;
import com.benz.project.pvm.http.vo.ResponseEntity;
import com.benz.project.pvm.service.VersionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/version")
public class GetVersion extends BaseController {

    @Autowired
    private VersionService versionService;

    private VersionEntity versionEntity;

    @RequestMapping(value="/get", method = RequestMethod.POST)
    public ResponseEntity handle(@RequestBody Map<String, Object> params) {
        ResponseEntity responseEntity = new ResponseEntity();
        Long handleStart = System.currentTimeMillis();
        try{
            handleDetail(params);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("project", this.getVersionEntity());
            responseEntity.setData(data);
        }catch(Exception e){
            responseEntity.setError(e.getMessage());
            responseEntity.setMessage("获取版本出错");
            responseEntity.setStatus(500);
        }finally{
            Long handleEnd = System.currentTimeMillis();
            responseEntity.setUseTime(handleEnd - handleStart);
            return responseEntity;
        }
    }

    private void handleDetail(Map<String, Object> params) throws Exception {
        String id = (String)params.get("id");
        Version version = versionService.getVersion(id);
        VersionEntity versionEntity = new VersionEntity();
        BeanUtils.copyProperties(versionEntity, version);
        this.setVersionEntity(versionEntity);
    }

    public VersionEntity getVersionEntity() {
        return versionEntity;
    }

    public void setVersionEntity(VersionEntity versionEntity) {
        this.versionEntity = versionEntity;
    }
}
